
#include <stdio.h>
#include <string.h>

// modbus 地址
#define MODBUS_ADDRESS ((uint8_t)1)
// modbus 按功能码解析数组元素大小
#define MODBUS_PARSER_BUILDER_SIZE ((uint8_t)5)

typedef char int8_t;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef int8_t (*modbus_sender_func)(uint8_t *data_in, uint16_t len);

#define FALSE (-1)
#define TRUE (0)

/* ModbusCRC16 余式表高字节 */
static const uint8_t crc16_modbus_h[] = {
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
    0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40};

/* ModbusCRC16 余式表低字节 */
static uint8_t crc16_modbus_l[] = {
    0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7,
    0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E,
    0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9,
    0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC,
    0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
    0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32,
    0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D,
    0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38,
    0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF,
    0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
    0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1,
    0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4,
    0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB,
    0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA,
    0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
    0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0,
    0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97,
    0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E,
    0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89,
    0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
    0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83,
    0x41, 0x81, 0x80, 0x40};

// modbus协议数据元
typedef struct modbus_node {
    uint8_t addr;       // 地址信息
    uint8_t cmd;        // 指令信息
    uint16_t reg_start; // 寄存器地址
    uint16_t reg_num;   // 寄存器个数
    uint8_t err_code;   // 错误码
    uint8_t data_bytes; // 数据个数，单位：uint8_t
    uint8_t res_bytes;  // 应答数据长度，用于发送数据入参
    uint8_t *data;      // 存放应用数据
} Modbus_node;

// modbus协议解析器和构建器
typedef struct modbus_parser_builder {
    uint8_t cmd;                                                         // 指令信息
    uint8_t head_len;                                                    // 打包数据头部长度,用于标记用户数据起点index,builder接口避免重复拷贝数据
    int8_t (*parser)(Modbus_node *node, uint8_t *data_in, uint16_t len); // 协议解析器
    int8_t (*handler)(Modbus_node *node);                                // 协议数据处理函数
    int8_t (*builder)(Modbus_node *node, uint8_t *data_out);             // 协议打包器
} Modbus_parser_builder;

// modbus管理
typedef struct modbus_manager {
    Modbus_node node;                                                  // modbus数据包管理
    Modbus_parser_builder parser_builders[MODBUS_PARSER_BUILDER_SIZE]; // 解析和打包器数组
    uint16_t (*crc)(uint8_t *data_in, uint16_t len);                   // crc校验
    int8_t (*input)(uint8_t *data_in, uint16_t len);                   // 数据输入函数
    modbus_sender_func sender;                                         // 应答数据抽象接口
    uint8_t *sender_buf;                                               // 发送数据缓冲区
} Modbus_manager;

// modbus功能码枚举
enum modbus_cmd {
    modbus_cmd_0x03,
    modbus_cmd_0x04,
    modbus_cmd_0x10
};

// modbus错误码枚举
enum modbus_err {
    modbus_err_no,
    modbus_err_crc,
    modbus_err_addr,
    modbus_err_cmd,
    modbus_err_parser_builder,
};

// 全局变量
static Modbus_manager modbus_manager;
static uint8_t modbus_sender_buf[256];

// CRC16-MODBUS校验
uint16_t modbus_crc(uint8_t *data_in, uint16_t len)
{
    uint8_t crc_h = 0xFF;
    uint8_t crc_l = 0xFF;
    uint8_t index;

    while (len--) {
        index = crc_h ^ *data_in++;
        crc_h = crc_l ^ crc16_modbus_h[index];
        crc_l = crc16_modbus_l[index];
    }

    return (uint16_t)((crc_h << 8) | crc_l);
}

// 按大端序打包数据流
int8_t modbus_build_big_endian(uint8_t *data_in, uint16_t reg_num, uint8_t *data_out)
{
    uint8_t i = 0;
    uint8_t index_hi = 0;
    uint8_t index_lo = 0;

    if (NULL == data_in || NULL == data_out || reg_num > 0x80)
        return FALSE;

    for (i = 0; i < reg_num; i++) {
        index_lo = i * 2;                       // 计算低位字节的索引
        index_hi = index_lo + 1;                // 计算高位字节的索引
        data_out[index_lo] = data_in[index_hi]; // 将高位字节复制到低位字节的位置
        data_out[index_hi] = data_in[index_lo]; // 将低位字节复制到高位字节的位置
    }

    return TRUE;
}

// 异常应答
int8_t modbus_build_err(Modbus_node *node, uint8_t *data_out)
{
    if (NULL == node || NULL == data_out)
        return FALSE;

    uint16_t crc = 0x0;

    data_out[0] = node->addr;
    data_out[1] = node->cmd;
    data_out[2] = node->err_code;
    crc = modbus_manager.crc(data_out, 3);
    data_out[3] = (uint8_t)(crc >> 8);
    data_out[4] = (uint8_t)crc;
    node->res_bytes = 5;

    return TRUE;
}

// modbus数据流输入处理
int8_t modbus_input(uint8_t *data_in, uint16_t len)
{
    if (NULL == data_in || len < 5)
        return FALSE;
    // 检查校验码
    uint16_t crc_check = (uint16_t)((data_in[len - 2] << 8) | data_in[len - 1]);

    if (modbus_manager.crc(data_in, len - 2) != crc_check) {
        modbus_manager.node.err_code = modbus_err_crc;
        goto MODBUS_INPUT_ERR;
    }

    // 检测地址
    if (data_in[0] != MODBUS_ADDRESS) {
        modbus_manager.node.err_code = modbus_err_addr;
        goto MODBUS_INPUT_ERR;
    }

    // modbus指令
    modbus_manager.node.addr = MODBUS_ADDRESS;
    modbus_manager.node.cmd = data_in[1];

    // 按照功能码找到匹配处理函数
    Modbus_parser_builder *parser_builder = NULL;
    for (uint8_t i = 0; i < MODBUS_PARSER_BUILDER_SIZE; i++) {
        if (modbus_manager.node.cmd == modbus_manager.parser_builders[i].cmd) {
            parser_builder = &modbus_manager.parser_builders[i];
            break;
        }
    }

    if (NULL == parser_builder) {
        modbus_manager.node.err_code = modbus_err_cmd;
        goto MODBUS_INPUT_ERR;
    }

    modbus_manager.node.err_code = modbus_err_parser_builder;
    // 解析modbus指令
    if (parser_builder->parser(&modbus_manager.node, data_in, len) != -1) {
        // 处理modbus数据
        if (parser_builder->handler(&modbus_manager.node) != -1) {
            // 打包modbus数据
            if (parser_builder->builder(&modbus_manager.node, modbus_manager.sender_buf) != -1) {
                modbus_manager.node.err_code = modbus_err_no;
            }
        }
    }

    // 输入错误处理
    if (modbus_manager.node.err_code != modbus_err_no) {
    MODBUS_INPUT_ERR: {
        modbus_manager.node.cmd |= 0x80;
        modbus_build_err(&modbus_manager.node, modbus_manager.sender_buf);
    }
    }

    // 应答modbus数据
    if (modbus_manager.sender(modbus_manager.sender_buf, modbus_manager.node.res_bytes) == -1)
        return FALSE;

    return TRUE;
}

/**
 * 处理modbus业务数据，后续添加功能可以参照一下个数
 * 1.添加一个功能码解析接口modbus_parser_xx(Modbus_node *node, uint8_t *data_in, uint16_t len)
 * 2.添加一个处理功能码对应用户数据modbus_handler_xx(Modbus_node *node)
 * 3.添加一个打包功能码对应用户数据modbus_builder_xx(Modbus_node *node, uint8_t *data_out)
 * 实例代码实现了0x03和0x10两个常用的功能码，其他的请参数标准modbus协议实现
 */
static uint8_t user_data[] = {0xA3, 0xB7, 0x60, 0xDC};
__weak int8_t modbus_handler_03_cb(Modbus_node *node)
{
    __unused(node);
}

int8_t modbus_parser_03_04(Modbus_node *node, uint8_t *data_in, uint16_t len)
{
    if (NULL == node || NULL == data_in || len != 8)
        return FALSE;

    node->data = NULL;
    node->data_bytes = 0;
    node->reg_start = (data_in[2] << 8) | data_in[3];
    node->reg_num = (data_in[4] << 8) | data_in[5];

    return TRUE;
}

int8_t modbus_handler_03(Modbus_node *node)
{
    // do somethings
    if (NULL == node)
        return FALSE;
    modbus_handler_03_cb();
    printf("modbus_handler_03 => cmd=0x%02x, reg_start=0x%02x, reg_num=0x%02x\n", node->cmd, node->reg_start, node->reg_num);
    if (modbus_build_big_endian(user_data, node->reg_num, &modbus_manager.sender_buf[modbus_manager.parser_builders[modbus_cmd_0x03].head_len]) == -1)
        return FALSE;
    node->data_bytes = node->reg_num << 1;

    return TRUE;
}

int8_t modbus_builder_03_04(Modbus_node *node, uint8_t *data_out)
{
    if (NULL == node || NULL == data_out)
        return FALSE;

    uint16_t crc = 0x0;

    data_out[0] = node->addr;
    data_out[1] = node->cmd;
    data_out[2] = node->data_bytes;
    crc = modbus_manager.crc(data_out, 3 + node->data_bytes);
    data_out[3 + node->data_bytes] = (uint8_t)(crc >> 8);
    data_out[4 + node->data_bytes] = (uint8_t)crc;

    node->res_bytes = (node->reg_num << 1) + 5;

    return TRUE;
}

int8_t modbus_handler_04(Modbus_node *node)
{
    // do somethings
    if (NULL == node)
        return FALSE;

    printf("modbus_handler_04 => cmd=0x%02x, reg_start=0x%02x, reg_num=0x%02x\n", node->cmd, node->reg_start, node->reg_num);
    if (modbus_build_big_endian(user_data, node->reg_num, &modbus_manager.sender_buf[modbus_manager.parser_builders[modbus_cmd_0x03].head_len]) == -1)
        return FALSE;
    node->data_bytes = node->reg_num << 1;

    return TRUE;
}
__weak int8_t modbus_handler_10_cb(Modbus_node *node)
{
    __unused(node);
}
int8_t modbus_parser_10(Modbus_node *node, uint8_t *data_in, uint16_t len)
{
    if (NULL == node || NULL == data_in || len < 6 || data_in[6] != (len - 9))
        return FALSE;

    node->data = data_in + 7;
    node->data_bytes = len - 9;
    node->reg_start = (data_in[2] << 8) | data_in[3];
    node->reg_num = (data_in[4] << 8) | data_in[5];

    return TRUE;
}

int8_t modbus_handler_10(Modbus_node *node)
{
    // do somethings
    if (NULL == node)
        return FALSE;
    modbus_handler_10_cb();
    printf("modbus_handler_10 => cmd=0x%02x, reg_start=0x%02x, reg_num=0x%02x, ", node->cmd, node->reg_start, node->reg_num);
    for (uint8_t i = 0; i < node->data_bytes; i++) {
        printf("data[%i]=%02x ", i, node->data[i]);
    }
    printf("\n");
    return 0;
}

int8_t modbus_builder_10(Modbus_node *node, uint8_t *data_out)
{
    if (NULL == node || NULL == data_out)
        return FALSE;

    uint16_t crc = 0x0;

    data_out[0] = node->addr;
    data_out[1] = node->cmd;
    data_out[2] = (uint8_t)(node->reg_start >> 8);
    data_out[3] = (uint8_t)node->reg_start;
    data_out[4] = (uint8_t)(node->reg_num >> 8);
    data_out[5] = (uint8_t)node->reg_num;
    crc = modbus_manager.crc(data_out, 6);
    data_out[6] = (uint8_t)(crc >> 8);
    data_out[7] = (uint8_t)crc;

    node->res_bytes = 8;

    return TRUE;
}

// 硬件层串口发送接口
int8_t uart_sender(uint8_t *data_in, uint16_t len)
{
    // 硬件抽象层接口发送数据，根据不同平台调用硬件串口发送数据接口
    if (NULL == data_in || len == 0)
        return FALSE;
    // for test
    printf("uart_sender=> ");
    for (size_t i = 0; i < len; i++) {
        printf("%02x ", data_in[i]);
    }
    printf("\n");

    return TRUE;
}

// 硬件层串口接受数据回调
int8_t on_uart_recv(uint8_t *data_in, uint16_t len)
{
    // 硬件抽象层接收数据接口
    modbus_manager.input(data_in, len);

    return TRUE;
}

static Modbus_manager modbus_manager =
    {
        .sender = uart_sender,
        .crc = modbus_crc,
        .input = modbus_input,
        .sender_buf = modbus_sender_buf,
        .parser_builders[modbus_cmd_0x03] = {
            .cmd = 0x03,
            .head_len = 0x03,
            .parser = modbus_parser_03_04,
            .handler = modbus_handler_03,
            .builder = modbus_builder_03_04,
        },
        .parser_builders[modbus_cmd_0x04] = {
            .cmd = 0x04,
            .head_len = 0x03,
            .parser = modbus_parser_03_04,
            .handler = modbus_handler_04,
            .builder = modbus_builder_03_04,
        },
        .parser_builders[modbus_cmd_0x10] = {
            .cmd = 0x10,
            .head_len = 0x05,
            .parser = modbus_parser_10,
            .handler = modbus_handler_10,
            .builder = modbus_builder_10,
        },
};

int main()
{
    // for test code=0x03
    uint8_t uart_recv_03[] = {0x01, 0x03, 0x10, 0xCE, 0x00, 0x02, 0xA1, 0x34};
    on_uart_recv(uart_recv_03, sizeof(uart_recv_03));
    // for test code=0x04
    uint8_t uart_recv_04[] = {0x01, 0x04, 0x70, 0x07, 0x00, 0x02, 0xDA, 0xCA};
    on_uart_recv(uart_recv_04, sizeof(uart_recv_04));
    // for test code=0x10
    uint8_t uart_recv_10[] = {0x01, 0x10, 0x10, 0xD6, 0x00, 0x03, 0x06, 0x00, 0x02, 0x00, 0x00, 0x00, 0x05, 0xEF, 0x35};
    on_uart_recv(uart_recv_10, sizeof(uart_recv_10));
    return 0;
}
